component extends="Controller" output="false" {
  
  public void function init(){
  }
  
  // players/index
  public void function index(){
    players = model("Player").findAll();
  }

  public void function byClub(){
    players = model("Player").findAllByClubId(params.key);
    renderPage(action="index");
  }
  
  // players/show/key
  public void function show(){
    player = model("Player").findByKey(params.key);
    	
    if (!IsObject(player)){
      flashInsert(error="Player #params.key# was not found");
      redirectTo(action="index");
    }
  }
  
  // players/new
  public void function new(){
    clubs = model("Clubs").findAll();
    player = model("Player").new();
  }
  
  //players/edit/key
  public void function edit(){
    clubs = model("Clubs").findAll();
    player = model("Player").findByKey(params.key);
    	
    if (!IsObject(player)){
	    flashInsert(error="Player #params.key# was not found");
			redirectTo(action="index");
	  }
  }
  
  // players/create
  public void function create(){
    player = model("Player").new(params.player);
		
		if (player.save()){
			flashInsert(success="The player was created successfully.");
      redirectTo(action="index");
		} else {
		  flashInsert(error="There was an error creating the player.");
		  renderPage(action="new");
		}
  }
  
  // players/update
  public void function update(){
    player = model("Player").findByKey(params.key);
		
		if (player.update(params.player)){
		  flashInsert(success="The player was updated successfully.");
      redirectTo(action="index");
		} else {
		  flashInsert(error="There was an error updating the player.");
			renderPage(action="edit");
		}
  }
  
  // players/delete/key
  public void function delete(){
    player = model("Player").findByKey(params.key);

		if (player.delete()){
			flashInsert(success="The player was deleted successfully.");
      redirectTo(action="index");
    } else {
      flashInsert(error="There was an error deleting the player.");
			redirectTo(action="index");
    }
  }

  public void function importJson() {

  }

  public void function doImportJson() {
    var tmpJsonData = {};    
    var sqlData = {};
    var sqlTeamData = '';
    var result = '';
    if(isJson(params.jsonData))
    {
      flashInsert(succes="Import completed");
      tmpJsonData = DeserializeJSON(params.jsonData);

      if(StructKeyExists(tmpJsonData,'lists'))
      {
        if(ArrayLen(tmpJsonData.lists))
        {
          sqlData = {};          
          for(playerIdx in tmpJsonData.lists) {
             // Player info
             if(StructKeyExists(playerIdx,'player'))
             {
              // Going to assume these fields all exist to save me writing more code
              sqlData['givenName'] = REReplace(playerIdx.player.givenName,"'","`","ALL");
              sqlData['surname'] = REReplace(playerIdx.player.surname,"'","`","ALL");
              sqlData['origin_playerId'] = playerIdx.player.playerId;
             }
             // Player stats
             if(StructKeyExists(playerIdx,'stats'))
             {
              sqlData['avg_fantasy_points'] = playerIdx.stats.averages.dreamTeamPoints;
              sqlData['cur_fantasy_points'] = playerIdx.stats.totals.dreamTeamPoints;
             }
             if(StructKeyExists(playerIdx,'team'))
             {
              sqlData['origin_teamId'] = playerIdx.team.teamId;
              sqlData['teamName'] = playerIdx.team.teamName;
              sqlData['teamNickname'] = playerIdx.team.teamNickname;
             }

             // Finished scrubbing the player data, lets append it into some sql scripts that we can use             
sqlTeamData = sqlTeamData & "
IF NOT EXISTS(SELECT 1 FROM clubs WHERE name = '#sqlData['teamName']#')
BEGIN
  INSERT INTO clubs (origin_clubId, name, club_nickname) 
  VALUES ('#sqlData['origin_teamId']#','#sqlData['teamName']#','#sqlData['teamNickname']#')
END
ELSE 
BEGIN
  UPDATE clubs 
  SET origin_clubId = '#sqlData['origin_teamId']#',
    club_nickname = '#sqlData['teamNickname']#'
  WHERE name = '#sqlData['teamName']#'
END
IF NOT EXISTS(SELECT 1 FROM players WHERE first_name='#sqlData['givenName']#' AND last_name='#sqlData['surname']#')
BEGIN
  INSERT INTO players (first_name, last_name, origin_playerId, avg_fantasy_points, cur_fantasy_points, clubid) 
  SELECT TOP 1 '#sqlData['givenName']#','#sqlData['surname']#','#sqlData['origin_playerId']#','#sqlData['avg_fantasy_points']#','#sqlData['cur_fantasy_points']#', c.id
  FROM clubs c WITH (NOLOCK)
  WHERE c.name = '#sqlData['teamName']#'
END
ELSE 
BEGIN
  UPDATE players 
  SET origin_playerId = '#sqlData['origin_playerId']#',
    avg_fantasy_points = '#sqlData['avg_fantasy_points']#',
    cur_fantasy_points = '#sqlData['cur_fantasy_points']#'
  WHERE first_name = '#sqlData['givenName']#' AND last_name = '#sqlData['surname']#'
END
";
             
          }    
        }
      }
      
      model("Player").runStaticBulkQuery(sqlTeamData);
    } else {
      flashInsert(succes="Error not JSON type");
    }    
    redirectTo(action='importJson');
  }
  
}
